//
//  DDPictureBrowserCell.swift
//  SinaMicroBlogSwift2
//
//  Created by dqw on 15/8/9.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

protocol DDScrollViewZoomDelegate: NSObjectProtocol {
    func didZoom(scale: CGFloat)
    func endZoom(scale: CGFloat)
}

// MARK: - 图片缩放的代理方法
extension DDPictureBrowserCell: UIScrollViewDelegate {
    
    func scrollViewDidZoom(scrollView: UIScrollView) {
        delegate?.didZoom(imageView.transform.a)
    }
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        layoutImageView2(view!.frame.size)
        delegate?.endZoom(scale)
    }
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }
}

class DDPictureBrowserCell: UICollectionViewCell {
    
    weak var delegate: DDScrollViewZoomDelegate?
    var imageUrl: NSURL? {
        didSet {
            resetScrollView()
            indicatorView.startAnimating()
            imageView.sd_setImageWithURL(imageUrl) { (image, _, _, _) -> Void in
                self.indicatorView.stopAnimating()
                self.indicatorView.hidden = true
                
                if  image == nil {
                    SVProgressHUD.showErrorWithStatus("图片下载错误")
                    return
                }
                
                self.layoutImageView2(self.getImageSize(image))
//                self.layoutImageView(image)
            }
        }
    }
    

    // MARK: - 图片布局清零
    private func resetScrollView() {
        imageView.image = nil
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentSize = CGSizeZero
        scrollView.contentOffset = CGPointZero
        scrollView.transform = CGAffineTransformIdentity
    }
    
    // MARK: - 布局图片 
    private func layoutImageView(image: UIImage) {
        let s = getImageSize(image)
        let height = scrollView.bounds.height
        if s.height <  height {
            let y = (height - s.height) * 0.5
            imageView.frame  = CGRect(origin: CGPointZero, size: s)
            scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: y, right: 0)
        }else{
            imageView.frame = CGRect(origin: CGPointZero, size: s)
            scrollView.contentSize = s
        }
        print(scrollView.contentOffset)
    }
    //MARK: - Cell的重用，transform 和 子控件 frame的重用。
    private func layoutImageView2(size: CGSize) {
        let s = size
        var offsetX = (UIScreen.mainScreen().bounds.width - s.width) * 0.5
        var offsetY = (UIScreen.mainScreen().bounds.height - s.height) * 0.5
        
        offsetX = offsetX > 0 ? offsetX : 0
        offsetY = offsetY > 0 ? offsetY : 0
        print(imageView.transform)
        print(imageView.frame)
        imageView.frame = CGRect(origin: CGPointZero, size: s)
        scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)
        
//        scrollView.contentSize = s

        if offsetX > 0 || offsetY > 0 {
            scrollView.contentSize = s
        }
        print(imageView.transform)
        print(imageView.frame)
    }
    private func getImageSize(image: UIImage) -> CGSize {
        let s = image.size
//        let width = scrollView.bounds.width
        let width = UIScreen.mainScreen().bounds.width
        let height = width * (s.height / s.width)
        return CGSize(width: width, height: height)
    }
    // MARK: -  初始化方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        configureScrollView()
        configureImageView()
        configureIndicatorView()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //MARK: - 加载布局子控件
    private func configureScrollView() {
        contentView.addSubview(scrollView)
        
        scrollView.delegate = self
        scrollView.minimumZoomScale = 0.5
        scrollView.maximumZoomScale = 2
        scrollView.pagingEnabled = true
        scrollView.bounces = false
        let dict = ["sv": scrollView, "iv": imageView]
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[sv]-20-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[sv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
    
    }
    private func configureImageView() {
        scrollView.addSubview(imageView)
        
//        let dict = ["sv": scrollView, "iv": imageView]
//        imageView.translatesAutoresizingMaskIntoConstraints = false
//        scrollView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[iv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
//        scrollView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[iv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
    }
    private func configureIndicatorView() {
        
        contentView.addSubview(indicatorView)
        indicatorView.tintColor = UIColor.redColor()
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraint(NSLayoutConstraint(item: indicatorView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
        contentView.addConstraint(NSLayoutConstraint(item: indicatorView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0))
 
    }
    

    
    // MARK: -   懒加载控件
    private lazy var scrollView = UIScrollView()
     lazy var imageView = UIImageView()
    private lazy var indicatorView = UIActivityIndicatorView()

    
}




